<?php
declare (strict_types=1);

namespace addons\Sms\driver;

use addons\Sms\exception\SmsException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Client;

class Sms
{
    /**
     * @param $mobile - 要发送的手机号
     * @param $content - 发送的内容，不含签名
     * @param int $time
     * 原点 2022年1月6日09:31:37 发送验证码
     */
    public function send($mobile, $content, $time = 300)
    {
        $uri = 'https://api.mix2.zthysms.com/v2/sendSms';

        $config = config('sms');

        $tkey = time();

        $param = [
            'tKey' => $tkey,
            'mobile' => $mobile,
            'content' => $config['sms_sign'] . $content,
            'username' => $config['sms_username'],
            'password' => md5(md5($config['sms_password']) . $tkey),
            'action' => 'send',
        ];

        try {
            $headers = [
                'Content-Type' => 'application/json',
            ];
            $res = (new Client())->request('POST', $uri, ['json' => $param, 'headers' => $headers]);

            return json_decode($res->getBody()->getContents(), true);

        } catch (RequestException $e) {
            if ($e->hasResponse()) {
                $response = $e->getResponse();
                throw new SmsException($response->getStatusCode(), $response->getBody()->getContents());
            }
            throw $e;
        }
    }


}